package com.yang.leather.admin.action.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;

import com.yang.leather.admin.action.BaseAction;
import com.yang.leather.admin.pojo.ImgsDel;
import com.yang.leather.common.store.IImgsDelService;
import com.yang.leather.common.struts2.ContextPvd;
import com.yang.leather.common.upload.UploadException;
import com.yang.leather.common.upload.UploadRule;
import com.yang.leather.common.upload.IUploadService;
import com.yang.leather.common.upload.UploadRule.UploadFile;
import com.yang.leather.common.util.ComUtils;

/**
 * 如果类有ckeditor编辑框上传图片功能，则继承此类
 * @author laoliu
 *
 */
public abstract class BaseUploadAction  extends BaseAction {
	private static final long serialVersionUID = 1L;
	
	private static final String _imgs_before_update_val = "_imgs_before_update_val";

	@Autowired
	protected ContextPvd contextPvd;
	@Autowired
	protected IImgsDelService imgsDelService;
	
	protected String uploadRuleId;
	
	protected String uploadType;
	
	/**
	 * 在新增时调用,设置上传规则
	 */
	public void addUploadRule(){
		UploadRule rule = new UploadRule();
		uploadRuleId = rule.getUploadRuleId();
		contextPvd.setSessionAttr(UploadRule.KEY + uploadRuleId, rule);
		
		addUploadType();
	}
	
	/**
	 * 在修改时调用,设置上传规则
	 */
	public void addUploadRuleBeforeUpd(String content){
		UploadRule rule = new UploadRule();
		uploadRuleId = rule.getUploadRuleId();
		contextPvd.setSessionAttr(UploadRule.KEY + uploadRuleId, rule);
		
		addUploadType();
		beforeUpdAddEditorImg(content);
	}
	
	/**
	 * 更新前，保存编辑框里图片路径
	 * @param content  编辑框内容
	 */
	private void beforeUpdAddEditorImg(String content){
		//可以加上一串MD5加密的字符串，便于删除时比较
		this.getRequest().setAttribute(_imgs_before_update_val, parseEditorContent(content));
	}

	/**
	 * 返回来自品牌币的图片
	 */
	private String parseEditorContent(String content){
		StringBuilder builder = new StringBuilder();
		
		if(StringUtils.isNotEmpty(content)){
			Document doc = Jsoup.parseBodyFragment(content);
			Elements links = doc.getElementsByTag("img");
			for(Element link : links) {
				String src = link.attr("src"); 
				if(StringUtils.isNotEmpty(src)){
					src = src.replace(".jpg", "");
					builder.append(src).append(";");
				}
			}
		}
		
		return builder.toString();
	}
	
	/**
	 * 保存、更新时调用.需判断编辑框图片是否改变
	 * 更新时，如果file表单里  保存的图片跟更新前图片不一致，需调用此方法来删除更新前的图片
	 * @param content ckeditor编辑框内容
	 * @param pics  图片路径(filePath+fileName)
	 */
	public void removeUploadRule(String content,String... pics) throws UploadException{
		if(StringUtils.isEmpty(uploadRuleId)){
			throw new UploadException(IUploadService.NO_RULE_ID,"没有上传规则");
		}
		UploadRule rule = (UploadRule)contextPvd.getSessionAttr(UploadRule.KEY + uploadRuleId);
		if(rule==null){
			throw new UploadException(IUploadService.NO_RULE_ID,"没有上传规则");
		}
		
		List<ImgsDel> list = afterUpdAddRemoveFile(pics);
		
		if(rule.getUploadFiles()!=null && rule.getUploadFiles().size()>0){
			String afterUpdEditorImgs = parseEditorContent(content);
			
			Map<String,UploadFile> map = new HashMap<String,UploadFile>();
			for(UploadFile file : rule.getUploadFiles()){
				map.put(file.getFilePath()+file.getFileName(), file);
			}
			
			if(StringUtils.isNotEmpty(afterUpdEditorImgs)){
				for(String pic : afterUpdEditorImgs.split(";")){
					if(map.get(pic)!=null){
						map.remove(pic);
					}
				}
			}
			
			//删除图片
			if(map!=null&&map.size()>0){
				for(UploadFile file : map.values()){
					ImgsDel del = new ImgsDel();
					del.setFilePath(file.getFilePath());
					del.setFileName(file.getFileName());
					del.setCreateDate(ComUtils.now());
					list.add(del);
				}
			}
		}else{
			String imgs_before_update_val = this.getRequest().getParameter(_imgs_before_update_val);
			String afterUpdEditorImgs = parseEditorContent(content);
			if(StringUtils.isNotEmpty(imgs_before_update_val)){
				for(String pic : imgs_before_update_val.split(";")){
					boolean isExist = false;
					if(StringUtils.isNotEmpty(afterUpdEditorImgs)){
						if(afterUpdEditorImgs.indexOf(pic)>-1){
							isExist = true;
						}
					}
					if(!isExist){
						String filePath = pic.substring(0,pic.lastIndexOf("/"));
						String fileName = pic.substring(pic.lastIndexOf("/")+1);
						ImgsDel del = new ImgsDel();
						del.setFilePath(filePath);
						del.setFileName(fileName);
						del.setCreateDate(ComUtils.now());
						list.add(del);
					}
				}
			}
		}
		
		if(list.size()>0){
			imgsDelService.batchSave(list);
		}
		// 清除上传规则
		contextPvd.removeAttribute(UploadRule.KEY + uploadRuleId);
	}
	
	/**
	 * 更新时，如果保存的图片跟更新前图片不一致，需调用此方法来删除更新前的图片
	 * @param pics  图片路径(filePath+fileName)
	 */
	private List<ImgsDel> afterUpdAddRemoveFile(String... pics){
		List<ImgsDel> list = new ArrayList<ImgsDel>();
		if(pics!=null && pics.length>0){
			for(String pic : pics){
				String filePath = pic.substring(0,pic.lastIndexOf("/"));
				String fileName = pic.substring(pic.lastIndexOf("/")+1);
				ImgsDel del = new ImgsDel();
				del.setFilePath(filePath);
				del.setFileName(fileName);
				del.setCreateDate(ComUtils.now());
				list.add(del);
			}
		}
		return list;
	}
	
	//设置uploadType类型
	public abstract void addUploadType();

	public String getUploadRuleId() {
		return uploadRuleId;
	}

	public void setUploadRuleId(String uploadRuleId) {
		this.uploadRuleId = uploadRuleId;
	}

	public String getUploadType() {
		return uploadType;
	}

	public void setUploadType(String uploadType) {
		this.uploadType = uploadType;
	}
}
